package org.walklink.core.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.walklink.common.util.*;
import org.walklink.core.config.Config;
import org.walklink.core.config.ConfigHelper;
import org.walklink.common.enums.EventTypeEnum;
import org.walklink.core.event.EventHandlerStrategy;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * 客户端初始化
 *
 * @author lidishan
 */
public class ClientInitializer {

    private static final Logger LOGGER = LoggerFactory.getLogger(ClientInitializer.class);

    /**
     * 初始化客户端信息
     */
    public static void init() {
        // TODO:  心跳检测
        startTaskMillSec(EventTypeEnum.HEARTBEAT,
                ConfigHelper.getInt(Config.SCHEDULE_HEARTBEAT_DELAY_TIME_MILLISECONDS, 5000));
        // TODO: 获取路由注册信息
        startTaskMillSec(EventTypeEnum.TOPIC_QUERY,
                ConfigHelper.getInt(Config.SCHEDULE_TOPIC_QUERY_DELAY_TIME_MILLISECONDS, 60000));
        // 收集JVM信息
        startTaskMillSec(EventTypeEnum.JVM_SYN,
                ConfigHelper.getInt(Config.SCHEDULE_JVM_DELAY_TIME_MILLISECONDS, 60000));
    }

    /**
     * 启动任务
     * @param typeEnum 事件枚举
     * @param periodTime 每秒执行次数
     */
    private static void startTaskMillSec(EventTypeEnum typeEnum, Integer periodTime) {
        startTask(typeEnum, periodTime, TimeUnit.MILLISECONDS);
    }
    private static void startTask(EventTypeEnum typeEnum, Integer periodTime, TimeUnit unit) {
        // 从当前秒取证开始运行
        long initialDelay = 60 - LocalDateTime.now().getSecond();

        // 启动任务
        LOGGER.debug("startTask schedule start typeEnum={} periodTime={} unit={}", typeEnum.name(), periodTime, unit.name());
        ThreadFactoryUtil.newSingleSchedule(typeEnum.name()).scheduleAtFixedRate(() -> {
            try {
                EventHandlerStrategy.select(typeEnum).send();
            } catch (Exception e) {
                LOGGER.error("startTask error typeEnum={} periodTime={} unit={} initialDelay={}",
                        typeEnum.name(), periodTime, unit, initialDelay, e);
            }
        }, initialDelay, periodTime, unit);
        LOGGER.debug("startTask schedule end typeEnum={} periodTime={} unit={}", typeEnum.name(), periodTime, unit.name());
    }

}
